<template>
  <div class="user-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button 
            type="primary" 
            icon="el-icon-plus" 
            @click="handleAddUser"
          >
            添加用户
          </el-button>
        </div>
      </template>
      
      <!-- 用户列表 -->
      <div v-if="!loading" class="user-list">
        <el-table :data="users" style="width: 100%">
          <el-table-column prop="id" label="用户ID" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="role" label="角色">
            <template #default="{ row }">
              <el-tag :type="row.role === 'admin' ? 'warning' : 'success'">
                {{ row.role === 'admin' ? '管理员' : '普通用户' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="创建时间" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleEditUser(row)"
                :disabled="row.role === 'admin' && !isCurrentUserAdmin"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDeleteUser(row.id)"
                :disabled="row.id === currentUserId || (row.role === 'admin' && !isCurrentUserAdmin)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 加载中 -->
      <div v-else class="loading-state">
        <el-loading :visible="true" text="加载用户中..." />
      </div>
    </el-card>
    
    <!-- 用户编辑对话框 -->
    <el-dialog
      :title="editingUser ? '编辑用户' : '添加用户'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form ref="userForm" :model="userForm" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username" :disabled="!!editingUser">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editingUser">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色" :disabled="!isCurrentUserAdmin">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSaveUser" :loading="saving">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, inject } from 'vue'
import { userApi } from '../services/api'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'UserManagement',
  setup() {
    const userStore = inject('userStore')
    const users = ref([])
    const loading = ref(true)
    const saving = ref(false)
    const dialogVisible = ref(false)
    const editingUser = ref(null)
    
    const userForm = reactive({
      username: '',
      password: '',
      role: 'user'
    })
    
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 50, message: '用户名长度应在 3 到 50 个字符之间', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }
    
    // 当前用户ID
    const currentUserId = computed(() => userStore.currentUser.value?.id || '')
    
    // 当前用户是否为管理员
    const isCurrentUserAdmin = computed(() => userStore.isAdmin.value)
    
    // 加载用户列表
    const loadUsers = async () => {
      try {
        loading.value = true
        const response = await userApi.getAllUsers()
        users.value = response.data || []
      } catch (error) {
        console.error('加载用户列表失败:', error)
        ElMessage.error('加载用户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 添加用户
    const handleAddUser = () => {
      editingUser.value = null
      // 重置表单
      userForm.username = ''
      userForm.password = ''
      userForm.role = 'user'
      dialogVisible.value = true
    }
    
    // 编辑用户
    const handleEditUser = (user) => {
      editingUser.value = user
      // 填充表单
      userForm.username = user.username
      userForm.role = user.role
      dialogVisible.value = true
    }
    
    // 保存用户
    const confirmSaveUser = async () => {
      try {
        // 表单验证
        if (!userForm.username || (!editingUser.value && !userForm.password) || !userForm.role) {
          ElMessage.warning('请填写必填项')
          return
        }
        
        saving.value = true
        
        if (editingUser.value) {
          // 更新用户
          await userApi.updateUser(editingUser.value.id, {
            role: userForm.role
          })
          ElMessage.success('用户更新成功')
        } else {
          // 创建用户
          await userApi.createUser({
            username: userForm.username,
            password: userForm.password,
            role: userForm.role
          })
          ElMessage.success('用户创建成功')
        }
        
        dialogVisible.value = false
        loadUsers() // 重新加载列表
      } catch (error) {
        console.error('保存用户失败:', error)
        ElMessage.error(error.response?.data?.message || '保存用户失败')
      } finally {
        saving.value = false
      }
    }
    
    // 删除用户
    const handleDeleteUser = async (userId) => {
      if (userId === currentUserId.value) {
        ElMessage.warning('不能删除当前登录用户')
        return
      }
      
      try {
        await ElMessageBox.confirm(
          '确定要删除该用户吗？',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await userApi.deleteUser(userId)
        ElMessage.success('用户删除成功')
        loadUsers() // 重新加载列表
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败:', error)
          ElMessage.error('删除用户失败')
        }
      }
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadUsers()
    })
    
    return {
      users,
      loading,
      saving,
      dialogVisible,
      editingUser,
      userForm,
      rules,
      currentUserId,
      isCurrentUserAdmin,
      handleAddUser,
      handleEditUser,
      confirmSaveUser,
      handleDeleteUser
    }
  }
}
</script>

<style scoped>
.user-management-container {
  padding: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.user-list {
  margin-top: 15px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .user-management-container {
    padding: 8px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .card-header .el-button {
    width: 100%;
  }
  
  .user-list {
    margin-top: 15px;
  }
  
  /* 调整表格在小屏幕上的显示 */
  :deep(.el-table) {
    font-size: 13px;
    min-width: 500px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 8px;
  }
  
  /* 调整操作按钮在小屏幕上的显示 */
  :deep(.el-table .el-button-group) {
    display: flex;
    flex-direction: column;
    gap: 5px;
    width: 100%;
  }
  
  :deep(.el-table .el-button) {
    width: 100%;
  }
  
  /* 调整对话框在小屏幕上的宽度 */
  :deep(.el-dialog) {
    width: 90% !important;
    margin-left: 5% !important;
  }
}

@media (max-width: 480px) {
  /* 进一步调整在极小屏幕上的显示 */
  .card-header {
    gap: 8px;
  }
  
  /* 优化表格在极小屏幕上的显示 */
  :deep(.el-table) {
    font-size: 12px;
    min-width: 400px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 6px;
  }
  
  /* 调整按钮尺寸 */
  :deep(.el-button) {
    padding: 6px 10px;
    font-size: 12px;
  }
  
  /* 调整对话框表单在极小屏幕上的显示 */
  :deep(.el-dialog .el-form) {
    width: 100%;
  }
  
  :deep(.el-dialog .el-form-item__label) {
    width: 80px;
    font-size: 13px;
  }
  
  :deep(.el-dialog .el-form-item__content) {
    width: calc(100% - 80px);
  }
  
  /* 确保表单元素在对话框中完全可见 */
  :deep(.el-dialog .el-input),
  :deep(.el-dialog .el-select) {
    width: 100%;
  }
  
  /* 调整对话框底部按钮的显示 */
  :deep(.el-dialog__footer .dialog-footer) {
    display: flex;
    gap: 10px;
  }
  
  :deep(.el-dialog__footer .el-button) {
    flex: 1;
    width: auto;
  }
}
</style>